package cn.epsilon3.platform.tencent.ses.service.impl;

import cn.epsilon3.configBean.InitializingTencentSesPlatformConfig;
import cn.epsilon3.constant.Base;
import cn.epsilon3.domain.e3.po.E3TencentSesPlatFormFile;
import cn.epsilon3.exception.Epsilon3Exception;
import cn.epsilon3.platform.tencent.ses.service.E3TencentSesPlatform;
import cn.epsilon3.utils.AssertUtils;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSONObject;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.ses.v20201002.SesClient;
import com.tencentcloudapi.ses.v20201002.models.Attachment;
import com.tencentcloudapi.ses.v20201002.models.SendEmailRequest;
import com.tencentcloudapi.ses.v20201002.models.SendEmailResponse;
import com.tencentcloudapi.ses.v20201002.models.Template;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;

/**
 * @description 腾讯云SES平台服务
 *
 * @author: epsilon3
 * @date: 2024-01-17
 */

@Service
public class E3TencentSesPlatformImpl implements E3TencentSesPlatform {

    @Resource
    private InitializingTencentSesPlatformConfig tencentSesPlatformConfig;

    /**
     * 腾讯云SES平台 发送邮件
     *
     * @param destination 接收人邮件地址 最多50人
     * @param templateId  模板ID
     * @param sendParam   模板ID对应字段的数据
     * @param subject     邮件主题
     * @param files       附件
     */
    @Override
    public void sendEmail(String[] destination,
                          Long templateId,
                          JSONObject sendParam,
                          String subject,
                          List<E3TencentSesPlatFormFile> files) {
        Boolean enable = tencentSesPlatformConfig.getEnable();
        if (enable) {
            Credential cred = new Credential(tencentSesPlatformConfig.getSecretId(), tencentSesPlatformConfig.getSecretKey());
            SesClient client = new SesClient(cred, tencentSesPlatformConfig.getRegion());

            SendEmailRequest req = new SendEmailRequest();
            String fromEmailAddress = tencentSesPlatformConfig.getFromEmailAddress();
            AssertUtils.isBlank(fromEmailAddress, "sender's email address is empty");
            req.setFromEmailAddress(fromEmailAddress);
            String replyToAddresses = tencentSesPlatformConfig.getReplyToAddresses();
            if (StrUtil.isNotBlank(replyToAddresses)) {
                req.setReplyToAddresses("ReplyToAddresses");
            }
            if (ObjectUtil.isNull(destination) || Base.INT0 == destination.length) {
                throw new Epsilon3Exception("recipient's email address is empty");
            }
            req.setDestination(destination);
            Template template = new Template();
            AssertUtils.isNull(templateId, "templateId is empty");
            template.setTemplateID(templateId);
            String jsonString = sendParam.toJSONString();
            AssertUtils.isBlank(jsonString, "sendData is empty");
            template.setTemplateData(jsonString);
            req.setTemplate(template);
            AssertUtils.isBlank(subject, "subject is empty");
            req.setSubject(subject);

            if (CollectionUtil.isNotEmpty(files)) {
                List<Attachment> attachmentList = new ArrayList<>();
                files.forEach(fileMain -> {
                    Attachment attachment = new Attachment();

                    String fileName = fileMain.getFileName();
                    AssertUtils.isBlank(fileName, "fileName is empty");
                    File file = fileMain.getFile();
                    long length = file.length();
                    AssertUtils.isFalse(length > 1024 * 1024 * 4, "maximum file size is 4M");
                    try {
                        byte[] fileContent = Files.readAllBytes(file.toPath());
                        String base64String = Base64.getEncoder().encodeToString(fileContent);
                        attachment.setFileName(fileName);
                        attachment.setContent(base64String);
                        attachmentList.add(attachment);
                    } catch (Exception e) {
                        throw new Epsilon3Exception(e.getMessage());
                    }
                });
                req.setAttachments(new Attachment[attachmentList.size()]);
            }
            req.setTriggerType(Base.LONG1);

            try {
                SendEmailResponse resp = client.SendEmail(req);
                // TODO 异步存储平台调用日志

            } catch (Exception e) {
                throw new Epsilon3Exception(e.getMessage());
            }
        }
    }
}
